<?php

namespace app\api\controller;

use app\common\controller\Api;

/**
 * 优惠券使用和领取管理
 */
class CouponHistory extends Api
{
    // protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\CouponHistory;

    }
    /**
     * 我的列表
     *
     */
    public function index()
    {   

        $page = (int)$this->request->request('page');
        $page = empty($page) ? 0 : ($page - 1) * 10;
        
        $list = $this->model->field('use_status')->with(['coupon'])->where('user_id',$this->auth->id)->where('use_status',0)->limit($page,10)->select();
        foreach ($list as $row) {
            $row->getRelation('coupon')->visible(['name','type','goods_type','discount']);
        }
        $this->success('请求成功',$list);
    }

    // 领取优惠券
    public function add()
    {
        $id = (int)$this->request->request('id');
        $count = $this->model->where('user_id',$this->auth->id)->where('coupon_id',$id)->count();
        if($count){
            $this->error('你已经领取过该优惠券');
        }
        $data = [
            'coupon_id' => $id,
            'user_id' => $this->auth->id,
            'nickname'   => $this->auth->nickname,
            'get_type'   => 1,
        ];
        $this->model->create($data);
        $this->success('领取成功');
    }

    // 批量增加注册
    public static function save_all($user)
    {
        $data = db('coupon')->field('id as coupon_id')->where('type',1)->where('status',0)->select();
        if($data){
            foreach($data as &$v){
                $v['user_id'] = $user['id'];
                $v['nickname'] = $user['nickname'];
                $v['get_type'] = 0;
                $v['create_time'] = time();
            }
            $model = new \app\common\model\CouponHistory;
            $model->insertAll($data);
        }

    }
    
}
